package com.hpe.controller.teacher;

import com.github.pagehelper.PageInfo;
import com.hpe.common.Const;
import com.hpe.dao.BigQuestionMapper;
import com.hpe.pojo.*;
import com.hpe.service.BigQuestionService;
import com.hpe.service.ExamService;
import com.hpe.service.SClassService;
import com.hpe.service.ScoreService;
import com.hpe.util.ServerResponse;
import com.hpe.util.ToolUtil;
import com.hpe.vo.LSReadOverpapers;
import com.hpe.vo.UsualScores;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * Created by chunjie on 2017/9/26.
 */
@Controller
@RequestMapping("/teacher/correct")
public class TeacherCorrectController {

    @Autowired
    private ScoreService paperService;

    @Autowired
    private ExamService examService;

    @Autowired
    private SClassService stuclassService;

    @Autowired
    private BigQuestionService bigQuestionService;

    /**
     * @Author:TangWenhao
     * @Description:显示待阅卷列表。该功能是批阅一整张试卷
     * @Date:10:21 2017/10/9
     */
    @RequestMapping(method = RequestMethod.POST, value = "/show_read_over.do")
    @ResponseBody
    public ServerResponse<PageInfo> readOverPapers(HttpSession session, @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                                                   @RequestParam(name = "pageSize", defaultValue = "3") int pageSize,
                                                   @RequestParam(name = "stuClassId", defaultValue = "-1") int stuClassId) {
        // 搜索条件
        Teacher t = (Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        ServerResponse<PageInfo> response = paperService.findAllPapers(stuClassId, t.getId(), pageNum, pageSize);
        return response;
    }

    /**
     * @Author:TangWenhao
     * @Description:获取班级列表
     * @Date:18:55 2017/10/9
     */
    @RequestMapping(method = RequestMethod.POST, value = "/class_list.do")
    @ResponseBody
    public ServerResponse<PageInfo> classList(HttpSession session,
                                              @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                                              @RequestParam(name = "pageSize", defaultValue = "3") int pageSize) {
        Teacher t = (Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        return stuclassService.getClassesByTeacher(t.getId(),Const.ClassState.ONSCHOOL, pageNum, pageSize);
    }

    /**
     * @Author:TangWenhao
     * @Description:开始阅卷，展示页面
     * @Date:10:31 2017/10/9
     */
    @RequestMapping(method = RequestMethod.GET, value = "/open_papers.do")
    @ResponseBody
    public ModelAndView openPapers(@RequestParam("examId") int examId,
                                   @RequestParam("sId") int sId,
                                   @RequestParam(name = "stuClassId", defaultValue = "-1") int stuClassId,
                                   ModelAndView mv) {
        //todo 双主键已解决
        Score papers = paperService.findById(sId, examId);
        String titles = papers.getContenttitl();
        String ans = papers.getContentans();
        //拆分 简单 和 编程
        String[] titelsArrys = titles.split("@@@");
        String[] ansArray = ans.split("@@@");
        if (ansArray.length > 1) {
            String sigTitle = titelsArrys[0];
            String codeTitle = titelsArrys[1];
            String sigAns = ansArray[0];
            String codeAns = ansArray[1];
            String[] titles1 = sigTitle.split("~");
            int num1=0;
            if(!"".equals(titles1[0])){
                num1=titles1.length;
            }
            String[] titles2 = codeTitle.split("~");
            int num2=0;
            if(!"".equals(titles2[0])){
                num2=titles2.length;
            }
            String[] ans1 = sigAns.split("~");
            String[] ans2 = codeAns.split("~");
            mv.addObject("titles1", titles1);
            mv.addObject("titles2", titles2);
            mv.addObject("ans1", ans1);
            mv.addObject("ans2", ans2);
            // 标号。
            mv.addObject("num1", num1);
            mv.addObject("num2", num2);
            //附加 根据examId查询每个题的分值
            ServerResponse<Exam> response=examService.selectByPrimaryKey(examId);
            Exam exam=response.getData();
            mv.addObject("examScore1", exam.getScore1()/titles1.length);
            mv.addObject("examScore2", exam.getScore2()/titles2.length);
        }
        // 计算每道题目分数
        mv.addObject("papers", papers);
        mv.addObject("sId", sId);
        mv.addObject("examId", examId);
        mv.addObject("stuClassId", stuClassId);

        mv.setViewName("t-correct-exam-update");
        return mv;
    }

    /**
     * @Author:TangWenhao
     * @Description:阅卷提交成绩和阅卷人。
     * @Date:10:30 2017/10/9
     */
    @RequestMapping(method = RequestMethod.POST, value = "/update_papers.do")
    @ResponseBody
    public ModelAndView updatePapers(HttpSession session, @RequestParam("examId") int examId,
                                     @RequestParam("sId") int sId,
                                     @RequestParam("num1") String num1,
                                     @RequestParam("num2") String num2,
                                     @RequestParam(name = "stuClassId", defaultValue = "-1") int stuClassId,
                                     HttpServletRequest req, ModelAndView mv) {
        if (num1 == null || num1.equals("")) {    //防止num1为空
            num1 = "0";
        }
        double score1 = 0;
        for (int i = 0; i < Integer.valueOf(num1); i++) {
            String scoreStr = req.getParameter("jianScore" + i);
            if (!ToolUtil.containsOtherChar(scoreStr)) {            //防止分数包含除数字外的其他字符
                score1 += Double.valueOf(scoreStr).doubleValue();
            }
        }
        if (num2 == null || num2.equals("")) {    //防止num2为空
            num2 = "0";
        }
        double score2 = 0;
        for (int i = 0; i < Integer.valueOf(num2); i++) {
            String scoreStr = req.getParameter("bianScore" + i);
            if (!ToolUtil.containsOtherChar(scoreStr)) {            //防止分数包含除数字外的其他字符
                score2 += Double.valueOf(scoreStr).doubleValue();
            }
        }
        Score p = paperService.findById(Integer.valueOf(sId), Integer.valueOf(examId));
        //这里，注意与原有系统字段不同。
        p.setScore2(score1);
        p.setScore3(score2);
        if(p.getStatus()==null){
            p.setStatus(1);
        }else{
            p.setStatus(1+p.getStatus());// 已经阅完。
        }
        Teacher teacher=(Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        p.setSpare(teacher.getName());
        // 执行新增
        paperService.updatePagers(p);
        /*  //加上班级，保证前端页面显示当前班级的答卷列表
        if(stuClassId!=-1){
            SClass sClass = stuclassService.selectByPrimaryKey(stuClassId);
            mv.addObject("stuClassName", sClass.getName());
        }
        mv.addObject("stuClassId", stuClassId);*/

        //todo 在这里触发自动推算，examId是否必要?必要。
        //todo 根据上一个的部分数据，推算出下一张符合的答卷，如果未选择班级，则查该老师权限所在的班级
        Score papers=paperService.findNextPaper(stuClassId,examId,teacher.getId());
        if(papers!=null) {
            String titles = papers.getContenttitl();
            String ans = papers.getContentans();
            //拆分 简单 和 编程
            String[] titelsArrys = titles.split("@@@");
            String[] ansArray = ans.split("@@@");
            if (ansArray.length > 1) {
                String sigTitle = titelsArrys[0];
                String codeTitle = titelsArrys[1];
                String sigAns = ansArray[0];
                String codeAns = ansArray[1];
                String[] titles1 = sigTitle.split("~");
                String[] titles2 = codeTitle.split("~");
                String[] ans1 = sigAns.split("~");
                String[] ans2 = codeAns.split("~");
                mv.addObject("titles1", titles1);
                mv.addObject("titles2", titles2);
                mv.addObject("ans1", ans1);
                mv.addObject("ans2", ans2);
                int n1=0;
                if(!"".equals(titles1[0])){
                    n1=titles1.length;
                }
                int n2=0;
                if(!"".equals(titles2[0])){
                    n2=titles2.length;
                }
                // 标号。
                mv.addObject("num1", n1);
                mv.addObject("num2", n2);
                //附加 根据examId查询每个题的分值
                ServerResponse<Exam> response = examService.selectByPrimaryKey(examId);
                Exam exam = response.getData();
                mv.addObject("examScore1", exam.getScore1() / titles1.length);
                mv.addObject("examScore2", exam.getScore2() / titles2.length);
            }
            // 计算每道题目分数
            mv.addObject("papers", papers);
            mv.addObject("sId", sId);
            mv.addObject("examId", examId);
            mv.addObject("stuClassId", stuClassId);
            mv.addObject("warn", 0);
        }else{
            mv.addObject("warn", 1);
        }
        mv.setViewName("/t-correct-exam-update");
        return mv;
    }

    /**
     * @Author:XuShengJie
     * @Description:流水阅卷获取全部试卷
     * @Date:10:38 2017/10/10
     */
    @RequestMapping(method = RequestMethod.GET,value = "/ls_show_all.do")
    @ResponseBody
    public ServerResponse<PageInfo> lsShowAllParpers(HttpSession session,
                                                     @RequestParam(name = "pageNum",defaultValue = "1")int pageNum,
                                                     @RequestParam(name = "pageSize",defaultValue = "5")int pageSize,
                                                     @RequestParam(name = "deptName",defaultValue = "-3") Integer deptName,
                                                     @RequestParam(name = "queType",defaultValue = "-1") Integer queType){
        //默认表示查询所有
        if(deptName == -3){
            deptName = null;
        }
        if (queType == -1){
            queType = null;
        }
        return paperService.lsFindAllPapers(deptName,queType,pageNum,pageSize);
    }

    @RequestMapping(method = RequestMethod.GET,value = "/ls_show_update.do")
    @ResponseBody
    public ModelAndView lsShowUpdate(RedirectAttributes redirectAttributes, ModelAndView modelAndView, LSReadOverpapers lsReadOverpapers) throws UnsupportedEncodingException {
        //String ntitle=new String(title.getBytes("ISO-8859-1"),"utf-8");
        Score score = paperService.findById(lsReadOverpapers.getsId(),lsReadOverpapers.geteId());
        if(score.getSpare().equals("0")&& score.getBigqueids().contains(String.valueOf(lsReadOverpapers.getBigQuestionId()))){
            //根据id获取题目信息
            score.setSpare("1");
            paperService.updatePagers(score);
            BigQuestion bigQuestion = bigQuestionService.getBQById(lsReadOverpapers.getBigQuestionId());
            modelAndView.addObject("examId",lsReadOverpapers.geteId());
            modelAndView.addObject("sId",lsReadOverpapers.getsId());
            modelAndView.addObject("title",bigQuestion.getTitle());
            String contentans = paperService.getAnsForPaper(lsReadOverpapers.geteId(),lsReadOverpapers.getsId(),lsReadOverpapers.getBigQuestionId());
            modelAndView.addObject("ans",contentans);
            modelAndView.addObject("type",lsReadOverpapers.getQueType());
            modelAndView.addObject("direct",lsReadOverpapers.getDirection());
            modelAndView.addObject("score",lsReadOverpapers.getBqScore());
            modelAndView.addObject("bzAns",bigQuestion.getContentans());
            modelAndView.addObject("bigQuestionId",bigQuestion.getId());
        }else{
            //找到下一个合适的题目
            LSReadOverpapers lsReadOverpapers1 = paperService.lsFindNextPaper(lsReadOverpapers.getDirection(),lsReadOverpapers.getQueType(),String.valueOf(lsReadOverpapers.getBigQuestionId()),lsReadOverpapers.geteId());
            if(lsReadOverpapers1 == null){
                redirectAttributes.addFlashAttribute("alertMsg", "所有试卷的该题目已批阅完成，并且该试卷正在被其他教师批改中");
                modelAndView.addObject("alertMsg","所有试卷的该题目已批阅完成，并且该试卷正在被其他教师批改中");
                modelAndView.setViewName("forward:/t-lscorrect.do");
                return modelAndView;
            }else{
                score = paperService.findById(lsReadOverpapers1.getsId(),lsReadOverpapers1.geteId());
                score.setSpare("1");
                paperService.updatePagers(score);
                BigQuestion bigQuestion = bigQuestionService.getBQById(lsReadOverpapers1.getBigQuestionId());
                modelAndView.addObject("examId",lsReadOverpapers1.geteId());
                modelAndView.addObject("sId",lsReadOverpapers1.getsId());
                modelAndView.addObject("title",bigQuestion.getTitle());
                String contentans = paperService.getAnsForPaper(lsReadOverpapers1.geteId(),lsReadOverpapers1.getsId(),lsReadOverpapers1.getBigQuestionId());
                modelAndView.addObject("ans",contentans);
                modelAndView.addObject("type",lsReadOverpapers1.getQueType());
                modelAndView.addObject("direct",lsReadOverpapers1.getDirection());
                modelAndView.addObject("score",lsReadOverpapers1.getBqScore());
                modelAndView.addObject("bzAns",bigQuestion.getContentans());
                modelAndView.addObject("bigQuestionId",bigQuestion.getId());
            }
        }
        modelAndView.setViewName("forward:/t-lscorrectgf.do");
        return modelAndView;
    }
    @RequestMapping(method = RequestMethod.POST,value = "/ls_update.do")
    @ResponseBody
    public ModelAndView lsUpdate(ModelAndView modelAndView,
                                 @RequestParam(name = "eId") int examId,
                           @RequestParam(name = "sId") int sId,
                           @RequestParam(name = "type") String type,
                               @RequestParam(name = "direct") String direct,
                           @RequestParam(name = "score") String score ,
                                 @RequestParam(name = "zscore") String zscore,
                                @RequestParam(name = "bigQuestionId") String bigQuestionId){
        Object result = paperService.lsUpdateScore(examId,sId,type,direct,score,bigQuestionId);
        if(result instanceof  String) {
            //全部改完
            modelAndView.setViewName("redirect:/t-lscorrect.do");
        }else{
            //下一道题

            LSReadOverpapers nextPaper = (LSReadOverpapers) result;
            Score nextScore = paperService.findById(nextPaper.getsId(),nextPaper.geteId());
            nextScore.setSpare("1");
            paperService.updatePagers(nextScore);
            modelAndView.addObject("examId",nextPaper.geteId());
            modelAndView.addObject("sId",nextPaper.getsId());
            modelAndView.addObject("title",nextPaper.getContentTitle());
            modelAndView.addObject("ans",nextPaper.getContentans());
            modelAndView.addObject("type",nextPaper.getQueType());
            modelAndView.addObject("direct",nextPaper.getDirection());
            modelAndView.addObject("score",zscore);
            modelAndView.addObject("bzAns",nextPaper.getBzAns());
            modelAndView.addObject("bigQuestionId",nextPaper.getBigQuestionId());
            modelAndView.setViewName("forward:/t-lscorrectgf.do");
        }
        return modelAndView;
    }

    /**
    * @Author:TangWenhao
    * @Description:为学生平时成绩打分，获取学生答卷相关信息列表
    * @Date:10:01 2017/10/12
    */
    @RequestMapping(method = RequestMethod.POST, value = "/show_usual.do")
    @ResponseBody
    public ServerResponse<PageInfo> usualScores(HttpSession session, @RequestParam(name = "pageNum", defaultValue = "1") int pageNum,
                                                   @RequestParam(name = "pageSize", defaultValue = "3") int pageSize,
                                                   @RequestParam(name = "stuClassId", defaultValue = "-1") int stuClassId) {
        // 搜索条件
        Teacher t = (Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        ServerResponse<PageInfo> response = paperService.findUsualScores(stuClassId, t.getId(), -1,pageNum, pageSize);
        return response;
    }

    /**
    * @Author:TangWenhao
    * @Description: 重新设计，消除半自动化打分
    * @Date:11:04 2017/10/12
    */
    @RequestMapping(method = RequestMethod.GET, value = "/open_usual.do")
    @ResponseBody
    public ServerResponse openUsual(HttpSession session) {
        UsualScores usualScores1 = (UsualScores) session.getAttribute("usualScores");
       return paperService.findUsualByClassAndExam(usualScores1.getClassId(),usualScores1.getExamId());
    }
    /*@RequestMapping(method = RequestMethod.GET, value = "/open_usual.do")
    @ResponseBody
    public ServerResponse<PageInfo> openUsual(  @RequestParam(name = "stuClassId", defaultValue = "-1") int stuClassId,
                                                HttpSession session) {
        UsualScores usualScores1 = (UsualScores) session.getAttribute("usualScores");
        Teacher t = (Teacher) session.getAttribute(Const.CURRENT_TEACHER);
        //默认有下一张
        ServerResponse<PageInfo> response;
        //关键在于第一次
        if("firstTime".equals(usualScores1.getTestName())){
            //查询所点击的同学，展开
            response=paperService.findUsualByStuExam(usualScores1.getClassId(),usualScores1.getsId(),usualScores1.getExamId(),1,1);
        }else{
            //取出可以打分的下一张。limit 0,1。不指定学生id,-2代表不指定，-1是默认值。
            response = paperService.findNextUsualScores(stuClassId, usualScores1.getExamId() ,1, 1);
            //推算得到下一位同学的Id
            if(response.getData().getList().size()>0){
                UsualScores usualScores = (UsualScores) response.getData().getList().get(0);
                usualScores1.setsId(usualScores.getsId());
            }
            session.setAttribute("usualScores",usualScores1);
        }
        return response;
    }*/

    /**
    * @Author:TangWenhao
    * @Description: 重新设计打分
    * @Date:11:36 2017/10/12
    */
    @RequestMapping(method = RequestMethod.POST, value = "/update_usual.do")
    @ResponseBody
    public ServerResponse updateUsual(@RequestParam(name = "str") String str,
                                      @RequestParam(name = "testName") String testName,
                                      HttpSession session) {
        UsualScores usualScores = (UsualScores) session.getAttribute("usualScores");
        //字段复用
        ServerResponse response=paperService.findUsualByClassAndExam(usualScores.getClassId(),usualScores.getExamId());
        String[] scoreM=str.split(",");
        List<UsualScores> list=(List<UsualScores>)response.getData();
        String msg="更新失败，请核对excel为当前考试";
        if(list.size()>0){
            //防止误操作,判断导入的是否为当前考试
            if(testName.equals(list.get(0).getTestName())){
                msg="更新成功";
                for(int i=0;i<list.size();i++){
                    Score p = paperService.findById(list.get(i).getsId(), usualScores.getExamId());
                    // 已经阅完。
                    if(p.getStatus()==null) {
                        p.setStatus(2);
                    }else {
                        p.setStatus(2 + p.getStatus());
                    }
                    p.setScoreM(Double.parseDouble(scoreM[i]));
                    // 执行更新
                    paperService.updatePagers(p);
                }
            }
        }
        return ServerResponse.createBySuccessMsg(msg);
    }
   /* @RequestMapping(method = RequestMethod.POST, value = "/update_usual.do")
    @ResponseBody
    public ServerResponse updateUsual(@RequestParam(name = "examId") int examId,
                              @RequestParam("scoreM") double scoreM,
                              HttpSession session) {
        UsualScores usualScores = (UsualScores) session.getAttribute("usualScores");
        //字段复用
        usualScores.setTestName("notFirstTime");
        session.setAttribute("usualScores",usualScores);
        Score p = paperService.findById(Integer.valueOf(usualScores.getsId()), Integer.valueOf(examId));
        p.setScoreM(scoreM);
        // 已经阅完。
        if(p.getStatus()==null) {
            p.setStatus(2);
        }else {
            p.setStatus(2 + p.getStatus());
        }
        // 执行新增
        paperService.updatePagers(p);
        return ServerResponse.createBySuccess("更新成功");
    }*/

    /**
    * @Author:TangWenhao
    * @Description:  某一班级的某一试卷的平时成绩导出
    * @Date:16:28 2017/11/10
    */
    @GetMapping("/usual_output_excel.do")
    public void outputExcel(HttpSession session,HttpServletRequest req, HttpServletResponse resp) throws Exception {
        UsualScores usualScores1 = (UsualScores) session.getAttribute("usualScores");
        paperService.outputExcelByUsual(req, resp, usualScores1.getClassId(), usualScores1.getExamId());
    }

    /**
    * @Author:TangWenhao
    * @Description: 导入平时成绩
    * @Date:10:38 2017/11/12
    */
    @RequestMapping(method = RequestMethod.POST,value = "/load_in_usual.do")
    @ResponseBody
    public ServerResponse loadinExcel(MultipartFile file) throws Exception {
        if (file == null) {
            return ServerResponse.createByErrorMsg("未获取到文件, 请重新上传");
        }
        //文件名
        String name = file.getOriginalFilename();
        //后缀
        String suffix = name.substring(name.indexOf("."));

        if (!".xls".equals(suffix) && !".xlsx".equals(suffix)) {
            return ServerResponse.createByErrorMsg("请选择.xls或者.xlsx后缀的文件");
        }

        InputStream inputStream = file.getInputStream();
        if (inputStream == null) {
            return ServerResponse.createByErrorMsg("输入流为空");
        }
        return paperService.loadinExcel(inputStream);
    }
}
